package com.itcast.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.itcast.pojo.*;
import com.itcast.service.*;
import com.itcast.util.OutUtil;
import com.alibaba.fastjson.JSON;
import org.apache.mahout.cf.taste.common.TasteException;
import java.io.File;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.EuclideanDistanceSimilarity;
import org.apache.mahout.cf.taste.impl.similarity.UncenteredCosineSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
import org.apache.mahout.common.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2020-06-19
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    /**
     * 商品
     */
    @Autowired(required = false)
    private Goodsservice goodsservice;

    /**
     * 图片集合
     */
    @Autowired(required = false)
    private Goodsimgservice goodsimgservice;

    /**
     *评论
     */
    @Autowired
    private Gcservice gcservice;
    @Autowired
    private Commontservice commontservice;

    /**
     * 用户
     */
    @Autowired(required = false)
    private Userservice userservice;






    @RequestMapping("/getGoodDate")
    public String goodsList(Model model,Integer page){
        QueryWrapper<Goods> queryWrapper=new QueryWrapper<>();
        Page<Goods> pageSize=new Page<>(page,6);
        IPage<Goods> goodlist = goodsservice.page(pageSize,null);
        model.addAttribute("goodlist",goodlist.getRecords());
        model.addAttribute("pre",goodlist.getCurrent()-1);
        model.addAttribute("next",goodlist.getCurrent()+1);
        model.addAttribute("cur",goodlist.getCurrent());
        model.addAttribute("last",goodlist.getPages());
        return "qd/goodDate3";
    }

    @RequestMapping("/findGoodsByCondition")
    public String findUserByCondition(Goods goods,
                                      @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                                      @RequestParam(value = "pageSize", defaultValue = "4") Integer pageSize, HttpServletRequest request) {
        PageInfo<Goods> pageInfoUsers = goodsservice.getGoodsWithPage1(pageIndex, pageSize,goods);
        request.setAttribute("goodlist", pageInfoUsers);
        return "qd/goodDate3";
    }



    /**
     * 首页
     * @param search
     * @return
     */
    @RequestMapping(value ="/search")
    public String search(String search, HttpServletResponse response, HttpSession session) {
        return  "redirect:/goods/index.html?search="+search;
    }

    @RequestMapping(value ="/index.html")
    public String indexModel(String search, Model model,HttpServletRequest request) {
        /**
         * 新品推荐
         */
        List<Goods> newGoodsList = goodsservice.newGoods(search);
        /**
         * 好品推荐
         */
       List<Goods>goodsList=goodsservice.goodProductsRank(search);
        /**
         * 热销产品
         */
       List<Goods> goodsListRank=goodsservice.selectproductsrank(search);
       if ((User) request.getSession().getAttribute("users")!=null){
           User user= (User) request.getSession().getAttribute("users");
           model.addAttribute("userName",user.getUserName());
       }
        model.addAttribute("newGoodsList", newGoodsList);
        model.addAttribute("goodsList", goodsList);
        model.addAttribute("goodsListRank", goodsListRank);
        return "qd/index";
    }


/*    *//**
     * 新品推荐带你条件分页
     *
     *//*
    @RequestMapping(value ="/searchHost")
    public String searchHost(Goods goods, HttpServletResponse response, HttpSession session) {
        return  "redirect:/goods/hostM?goods="+goods;
    }

    @RequestMapping(value ="/hostM")
    public String hostM( Goods goods, Model model) {//Map<String,String>
        List<Goods> newGoodsList = goodsservice.newGoods(goods.getGname());
        System.out.println(newGoodsList.size());
        model.addAttribute("newGoodsList", newGoodsList);
        return "qd/catalog_list";
    }*/

    /**
     * 商品详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value ="/getByIdGoods")
    public String getByIdGoods( Integer id, Model model,HttpServletResponse response) {//Map<String,String>
        Goods goods = goodsservice.getByIdGoods(id);//商品信息
        List<Goodsimg> listimg = goodsimgservice.getByGoodsId(id);//图片列表
        List<Goods>  listByItem=null;
        if (goods!=null){
            listByItem =goodsservice.getByItemGoods(goods.getItem());//类型查询
        }
       //List<Gc> gcList =gcservice.getByGid(id);//评论
        QueryWrapper<Commont> queryWrappera =new QueryWrapper<>();
        queryWrappera.eq("gid",id);
        List<Commont > gcList =commontservice.list(queryWrappera);
        List<Goods> goodsListT= goodsservice.getByPrice();//特价商品
        List<Goods> goodsListl = goodsservice.getByView();//浏览较多
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("listimg", listimg);
        String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
        model.addAttribute("listimg", json);
        model.addAttribute("goods", goods);
        model.addAttribute("listByItem",listByItem);
        model.addAttribute("gcList",gcList);
        model.addAttribute("goodsListl",goodsListl);
        model.addAttribute("goodsListT",goodsListT);
        /**
         * 增加浏览量
         */
        goods.setViews(goods.getViews()+1);
        QueryWrapper<Goods> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("gid",id);
        goodsservice.update(goods,queryWrapper);
        return "qd/product_page";
    }
    /**
     * 新推推荐，带条件分页
     * @param conditionData 条件
     * @return  查询成功返回PageInfo<Goods>对象，否则返回null
     */
    @ResponseBody
    @RequestMapping("/getGoodsByConditionAndPage")
    public PageInfo<Goods> getGoodsByConditionAndPage(@RequestBody Map<String,String> conditionData){
        if (conditionData == null)
            return null;
        PageInfo<Goods> goodsByConditionAndPage = goodsservice.getGoodsByConditionAndPage(conditionData);
        return goodsByConditionAndPage;
    }

    /**
     * 全部宝贝，带条件分页
     * @param conditionData
     * @return
     */
    @ResponseBody
    @RequestMapping("/getAllGoodsByConditionAndPage")
    public PageInfo<Goods> getAllGoodsByConditionAndPage(@RequestBody Map<String,String> conditionData){
        if (conditionData == null)
            return null;
        PageInfo<Goods> goodsByConditionAndPage = goodsservice.getAllGoodsByConditionAndPage(conditionData);
        return goodsByConditionAndPage;
    }

    /**
     * 热销品，带条件分页
     * @param conditionData
     * @return
     */
    @ResponseBody
    @RequestMapping("/getGoodsHotByConditionAndPage")
    public PageInfo<Goods>  getGoodsHotByConditionAndPage(@RequestBody Map<String,String> conditionData){
        if (conditionData == null)
            return null;
        PageInfo<Goods> goodsByConditionAndPage = goodsservice.getGoodsHotByConditionAndPage(conditionData);
        return goodsByConditionAndPage;
    }



    /**
     *
     * 特价商品
     * @return
     */
    @ResponseBody
    @RequestMapping("/getGoodsListT")
    public List<Goods> getGoodsListT(){
        List<Goods> goodsListT= goodsservice.getByPrice();//特价商品
        return goodsListT;
    }
    //推荐猜你喜欢
    @ResponseBody
    @RequestMapping("/note_list")
    public String  note_list(HttpServletRequest request,HttpServletResponse response,@RequestBody Map<String,String> conditionData) throws IOException, TasteException {

        User userId= (User) request.getSession().getAttribute("users");
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        if (userId != null) {
           // User u = (User) request.getSession().getAttribute("users");
            User u =userId;
            //基于用户的协同过滤算法
            //用户-物品-评分数据文件
            String file = "E:\\SpringBoot\\nxt\\src\\data\\test.txt";
            //数据模型
            DataModel model = new FileDataModel(new File(file));
            //欧几里得相似度
            UserSimilarity user = new EuclideanDistanceSimilarity(model);
            NearestNUserNeighborhood neighbor = new NearestNUserNeighborhood(6, user, model);//数字为限制几个推荐
            //定义推荐引擎
            Recommender r = new GenericUserBasedRecommender(model, neighbor, user);
            //获取用户Uid的推荐列表
            List<RecommendedItem> list = r.recommend(u.getUid(), 6);
            ArrayList<Integer> gid = new ArrayList<Integer>();
            for (RecommendedItem ritem : list) {
                System.out.printf("(%s,%f)", ritem.getItemID(), ritem.getValue());
                gid.add((int) ritem.getItemID());

            }
            //基于用户推荐+综合前四的商品
            if (gid.size() != 0) {
                List<Goods> prolike = goodsservice.selectproductsliketest(gid);
                List<Goods> prolike2 = goodsservice.selectproductslike3();
                prolike.removeAll(prolike2);
                prolike.addAll(prolike2);
                Set<Goods> ts = new HashSet<Goods>();
                ts.addAll(prolike);
               jsonMap.put("prolike", prolike);

            }
            //基于物品的协同过滤算法
            //余弦相似度
            ItemSimilarity itemSimilarity = new UncenteredCosineSimilarity(model);
            //定义推荐引擎
            Recommender recommender = new GenericItemBasedRecommender(model, itemSimilarity);
            int us = gcservice.selectlike(u.getUid());
            //刚刚登陆注册用户推荐综合前六的商品
            if (gid.size() == 0 && us == 0) {
                List<Goods> prolike = goodsservice.selectproductslike2();
                jsonMap.put("prolike", prolike);
            }
            if (us != 0) {
                List<RecommendedItem> list2 = recommender.recommend(u.getUid(), 6);  //获取推荐结果
                //遍历推荐结果
                ArrayList<Integer> gid2 = new ArrayList<Integer>();
                for (RecommendedItem ritem : list2) {
                    System.out.printf("(%s,%f)", ritem.getItemID(), ritem.getValue());
                    gid2.add((int) ritem.getItemID());
                }
                if (gid.size() != 0 && gid2.size() != 0) {
                    //基于用户推荐+基于物品推荐+综合前四的商品
                    List<Goods> prolike = goodsservice.selectproductsliketest(gid);
                    List<Goods> prolike2 = goodsservice.selectproductsliketest(gid2);
                    List<Goods> prolike3 = goodsservice.selectproductslike3();
                    //合并去重
                    prolike.removeAll(prolike2);
                    prolike.addAll(prolike2);
                    prolike.removeAll(prolike3);
                    prolike.addAll(prolike3);
                    Set<Goods> ts = new HashSet<Goods>();
                    ts.addAll(prolike);
                    jsonMap.put("prolike", prolike);
                    String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
                    OutUtil.outcase(json,response);
                }
                //基于物品推荐+综合前四的商品
                if (gid.size() == 0 && gid2.size() != 0) {
                    //基于用户推荐+基于物品推荐+综合前四的商品
                    List<Goods> prolike = goodsservice.selectproductsliketest(gid2);
                    List<Goods> prolike3 = goodsservice.selectproductslike3();
                    //合并去重
                    prolike.removeAll(prolike3);
                    prolike.addAll(prolike3);
                    Set<Goods> ts = new HashSet<Goods>();
                    ts.addAll(prolike);
                    jsonMap.put("prolike", prolike);
                    String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
                    OutUtil.outcase(json,response);
                }
                //基于用户推荐和基于物品推荐都为空时,推荐综合前六的商品
                if (gid.size() == 0 && gid2.size() == 0) {
                    List<Goods> prolike = goodsservice.selectproductslike2();
                    jsonMap.put("prolike", prolike);
                }
            }


        }else{
            List<Goods>  prolike = goodsservice.selectproductslike2();
            jsonMap.put("prolike", prolike);
        }
        String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
        OutUtil.outcase(json,response);
        return null;
    }
    @RequestMapping("/note_list2")
    public String note_list2(HttpServletResponse response){
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        List<Goods>  prolike = goodsservice.selectproductslike2();
        jsonMap.put("prolike", prolike);
        String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
        OutUtil.outcase(json,response);
        return null;
    }





}

